<?php
namespace com\rs\dns\controller\api;

use com\rs\dns\constant\CommonConstant;
use com\rs\dns\controller\api\vo\RecordBalanceForm;
use com\rs\dns\controller\BaseController;
use com\rs\dns\exception\BaException;
use com\rs\dns\service\RecordService;
use restphp\http\RestHttpRequest;
use restphp\http\RestHttpStatus;

/**
 * Class UserRecordBalanceController.
 * @package com\rs\dns\controller\api
 * @RequestMapping("/api/user/records")
 */
final class UserRecordBalanceController extends BaseController {
    /**
     * 获取列表.
     * @RequestMapping("/{recordId}/balances", method="GET")
     * @throws BaException
     */
    public function getList() {
        $recordId = RestHttpRequest::getPathValue("recordId");
        if (!RecordService::hadRecord($recordId, $this->_getUsername())) {
            throw new BaException(CommonConstant::NO_RIGHT_TO_OPERATING_THE_DATA, RestHttpStatus::Forbidden);
        }
        $arrList = RecordService::getBalanceList($recordId);
        $this->_success($arrList);
    }

    /**
     * 设置负载均衡.
     * @RequestMapping("/{recordId}/balances", method="POST")
     * @throws BaException
     */
    public function setBalance() {
        $recordId = RestHttpRequest::getPathValue("recordId");
        if (!RecordService::hadRecord($recordId, $this->_getUsername())) {
            throw new BaException(CommonConstant::NO_RIGHT_TO_OPERATING_THE_DATA, RestHttpStatus::Forbidden);
        }
        $balanceForm = RestHttpRequest::getBody(new RecordBalanceForm(), true);
        $arrId = array();
        foreach ($balanceForm->getAuxList() as $aux) {
            $arrId[] = $aux['id'];
        }
        if (!RecordService::hadRecords($arrId, $this->_getUsername())) {
            throw new BaException(CommonConstant::NO_RIGHT_TO_OPERATING_THE_DATA, RestHttpStatus::Forbidden);
        }
        RecordService::setBalance($balanceForm);
    }
}